﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Windows;
using System.Xml.Linq;
using ClientBankWPF.Entities;
using ClientBankWPF.Service;
using CryptoModule;
using DevExpress.Xpf.Core;

namespace ClientBankWPF
{
    /// <summary>
    /// Interaction logic for ClientAddWindow.xaml
    /// </summary>
    public partial class ClientAddWindow
    {
        private readonly DataAccessService dataAccessService;
        private readonly Generators generators;
        private readonly RSASignature rsaSignature;

        public Client NewClient { get; set; }

        public ClientAddWindow(DataAccessService dataAccessService)
        {
            InitializeComponent();
            this.dataAccessService = dataAccessService;
            generators = new Generators(dataAccessService);
            rsaSignature = new RSASignature();
            textBoxUNP.Text = generators.UNPGenerator().ToString();
        }

        public ClientAddWindow()
        {
            InitializeComponent();
        }

        private void ButtonCreateClientClick(object sender, RoutedEventArgs e)
        {
            try
            {
                if (!String.IsNullOrEmpty(textBoxClientName.Text))
                {
                    NewClient = dataAccessService.GetClient(textBoxClientName.Text);
                    if (NewClient == null)
                    
                    {
                        if (!String.IsNullOrEmpty(textBoxClientAddress.Text))
                        {
                            if (!String.IsNullOrEmpty(textBoxClientCFO.Text))
                            {
                                if (!String.IsNullOrEmpty(textBoxClientDescription.Text))
                                {
                                    SortedList<string, byte[]> keyPair = rsaSignature.GeneraitPair();
                                    NewClient = new Client
                                    {
                                        Address = textBoxClientAddress.Text,
                                        CFO = textBoxClientCFO.Text,
                                        Description = textBoxClientDescription.Text,
                                        Id = Guid.NewGuid(),
                                        Name = textBoxClientName.Text,
                                        UNP = generators.UNPGenerator(),
                                        OpenKey = keyPair["public"]
                                    };
                                    string result = dataAccessService.AddClient(NewClient);
                                    if (!String.IsNullOrEmpty(result))
                                    {
                                        DXMessageBox.Show(result, "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
                                    }
                                    else
                                    {
                                        Directory.CreateDirectory("ClientFilesStorage/" + NewClient.Name + "/");
                                        string path = "ClientFilesStorage/" + NewClient.Name + "/" + "privateKey";
                                        var fileStream = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.None);
                                        fileStream.Write(keyPair["private"], 0, keyPair["private"].Length);
                                        fileStream.Flush();
                                        fileStream.Close();
                                        var xDocument = new XDocument(
                                            new XComment("Current client information"),
                                            new XElement("Client",
                                                         new XElement("Name", NewClient.Name),
                                                         new XElement("UNP", NewClient.UNP),
                                                         new XElement("Id", NewClient.Id)));
                                        xDocument.Save("ClientFilesStorage/" + NewClient.Name + "/" + "clientInfo.xml");
                                        //clients.Add(client);
                                        DXMessageBox.Show("Клиент добавлен", "Информация", MessageBoxButton.OK, MessageBoxImage.Information);
                                        Close();
                                    }
                                }
                                else
                                {
                                    DXMessageBox.Show("Описание клиента не введено", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
                                }
                            }
                            else
                            {
                                DXMessageBox.Show("Имя главного бухгалтера не введено", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
                            }
                        }
                        else
                        {
                            DXMessageBox.Show("Адрес не введён", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
                        }
                    }
                    else
                    {
                        DXMessageBox.Show("Такой клиент уже существует", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
                        NewClient = null;
                    }
                }
                else
                {
                    DXMessageBox.Show("Имя клиента не введено", "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }
            catch (Exception exception)
            {
                DXMessageBox.Show(exception.Message, "Ошибка", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void ButtonCancelClick(object sender, RoutedEventArgs e)
        {
            Close();
        }
    }
}
